// ignore_for_file: dangling_library_doc_comments, slash_for_doc_comments
/*** 
 * @Author: Zhong
 * @Date: 2025-03-28 11:23:43
 * @LastEditors: Zhong zhongxiaodong@eenet.com
 * @LastEditTime: 2025-07-15 14:53:39
 * @FilePath: /wan_android_flutter/lib/common_code/widgets/countdown_btn.dart
 * @Description: 倒计时按钮
 */

import 'package:flutter/material.dart';
import 'dart:async';

class CountdownButton extends StatefulWidget {
  final String normalText;
  final String countdownText;
  final Color? buttonColor;
  final TextStyle normalTextStyle;
  final TextStyle countdownTextStyle;
  final Duration countdownDuration;
  final VoidCallback? onPressed;

  const CountdownButton({
    Key? key,
    required this.normalText,
    required this.countdownText,
    this.buttonColor,
    this.normalTextStyle = const TextStyle(),
    this.countdownTextStyle = const TextStyle(),
    this.countdownDuration = const Duration(seconds: 60),
    this.onPressed,
  }) : super(key: key);

  @override
  _CountdownButtonState createState() => _CountdownButtonState();
}

class _CountdownButtonState extends State<CountdownButton> {
  int _countdownTime = 0;
  Timer? _timer;
  bool _isCounting = false;

  void _startCountdown() {
    if (widget.onPressed != null) {
      widget.onPressed!();
    }
    setState(() {
      _countdownTime = widget.countdownDuration.inSeconds;
      _isCounting = true;
    });

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownTime > 0) {
          _countdownTime--;
        } else {
          _timer?.cancel();
          _isCounting = false;
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: _isCounting ? null : _startCountdown,
      style: ElevatedButton.styleFrom(
        backgroundColor: widget.buttonColor ?? Colors.transparent,
        foregroundColor: widget.buttonColor ?? Colors.transparent,
        disabledForegroundColor:
            widget.buttonColor != null ? Colors.grey : Colors.transparent,
        disabledBackgroundColor:
            widget.buttonColor != null ? Colors.grey : Colors.transparent,
        side: BorderSide.none,
        elevation: 0,
        // 设置不同状态下的阴影值为 0
        shadowColor: Colors.transparent,
        surfaceTintColor: Colors.transparent,
      ),
      child: Text(
        _isCounting
            ? '${_countdownTime} 秒后 ${widget.countdownText}'
            : widget.normalText,
        style: _isCounting ? widget.countdownTextStyle : widget.normalTextStyle,
      ),
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}
